<template>
  <div class="table-example">
    <el-card>
      <!-- 搜索表单 -->
      <search-form
        v-model="queryParams"
        @search="handleSearch"
        @reset="handleReset"
      >
        <el-form-item label="姓名">
          <el-input v-model="queryParams.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="queryParams.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
      </search-form>

      <!-- 表格 -->
      <pro-table
        ref="tableRef"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :total="total"
        @add="handleAdd"
        @edit="handleEdit"
        @delete="handleDelete"
        @batch-delete="handleBatchDelete"
        @selection-change="handleSelectionChange"
        @pagination="getList"
      >
        <!-- 自定义状态列 -->
        <template #status="{ row }">
          <el-tag :type="row.status === '1' ? 'success' : 'danger'">
            {{ row.status === "1" ? "启用" : "禁用" }}
          </el-tag>
        </template>

        <!-- 自定义操作列 -->
        <template #operation="{ row }">
          <el-button type="primary" link :icon="Edit" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="success" link :icon="View" @click="handleView(row)">
            查看
          </el-button>
          <el-button
            type="danger"
            link
            :icon="Delete"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </pro-table>
    </el-card>

    <!-- 表单对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="'1'">启用</el-radio>
            <el-radio :value="'0'">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { Edit, Delete, View } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import SearchForm from "@/components/SearchForm.vue";

// 表格列配置
const columns = [
  { prop: "name", label: "姓名", minWidth: 100 },
  { prop: "age", label: "年龄", width: 80, align: "center" },
  { prop: "email", label: "邮箱", minWidth: 160 },
  {
    prop: "status",
    label: "状态",
    width: 100,
    align: "center",
  },
];

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: "",
  age: undefined,
  status: "",
});

// 表格数据
const loading = ref(false);
const tableData = ref([]);
const total = ref(0);
const selectedRows = ref<any[]>([]);

// 获取表格数据
const getList = async () => {
  loading.value = true;
  try {
    // 模拟接口请求
    await new Promise((resolve) => setTimeout(resolve, 500));
    const list = Array.from({ length: 10 }).map((_, index) => ({
      id: index + 1,
      name: `用户${index + 1}`,
      age: Math.floor(Math.random() * 50) + 18,
      email: `user${index + 1}@example.com`,
      status: Math.random() > 0.5 ? "1" : "0",
    }));
    tableData.value = list;
    total.value = 100;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置
const handleReset = () => {
  queryParams.name = "";
  queryParams.age = undefined;
  queryParams.status = "";
  handleSearch();
};

// 表单对话框
const dialog = reactive({
  visible: false,
  title: "",
});

// 表单数据
const formRef = ref<FormInstance>();
const form = reactive({
  id: undefined,
  name: "",
  age: undefined,
  email: "",
  status: "1",
});

// 表单校验规则
const rules = {
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
};

// 新增
const handleAdd = () => {
  dialog.title = "新增用户";
  dialog.visible = true;
  form.id = undefined;
  form.name = "";
  form.age = undefined;
  form.email = "";
  form.status = "1";
};

// 编辑
const handleEdit = (row: any) => {
  dialog.title = "编辑用户";
  dialog.visible = true;
  Object.assign(form, row);
};

// 查看
const handleView = (row: any) => {
  ElMessage.success(`查看用户：${row.name}`);
};

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm("确认要删除该数据吗？", "提示", {
      type: "warning",
    });
    ElMessage.success("删除成功");
    getList();
  } catch {
    // 取消删除
  }
};

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确认要删除选中的 ${selectedRows.value.length} 条数据吗？`,
      "提示",
      {
        type: "warning",
      }
    );
    ElMessage.success("删除成功");
    getList();
  } catch {
    // 取消删除
  }
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    ElMessage.success(form.id ? "修改成功" : "新增成功");
    dialog.visible = false;
    getList();
  } catch (error: any) {
    ElMessage.error(error.message || (form.id ? "修改失败" : "新增失败"));
  }
};

// 初始化
getList();
</script>
